<?php

namespace app\common\service;

use app\common\exception\BusinessException;
use app\common\helper\WxBizDataHelper;
use app\common\helper\WxHelper;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use think\facade\Cache;
use think\facade\Config;
use Firebase\JWT\SignatureInvalidException;
use think\Exception;

class MpService
{
    /**
     * getAccessToken
     * @param string $appId
     * @param string $appSecret
     * @return string
     * @throws BusinessException
     */
    public static function getAccessToken(string $appId, string $appSecret): string
    {
        // api地址
        $api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";

        // response
        $response = file_get_contents($api);
        if (!$response) {
            throw new BusinessException('请求微信accessToken接口失败');
        }
        $responseData = json_decode($response, true);
        if (!$responseData) {
            throw new BusinessException('转换微信accessToken数据失败');
        }

        // check response
        if (!empty($responseData['errcode']) && $responseData['errcode'] !== 0) {
            throw new BusinessException($responseData['errmsg']);
        }

        //dump($responseData['access_token']);

        // return
        return $responseData['access_token'];
    }

    /**
     * addTempMaterial
     * @param $type
     * @param $media
     * @param $accessToken
     * @return mixed
     * @throws BusinessException
     */
    public static function addTempMaterial($type, $media, $accessToken)
    {
        // 文件Key
        $key = 'addTempMaterial_' . md5($media);
        $data = Cache::get($key);
        if ($data) {
            return $data;
        }

        // api地址
        $api = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$accessToken}";

        // 发起请求
        $sendData = [
            'type' => $type,
            'media' => new \CURLFile($media)
        ];
        $response = curl($api, $sendData, false);
        if (!$response) {
            throw new BusinessException('请求微信upload接口失败');
        }
        $responseData = json_decode($response, true);
        if (!$responseData) {
            throw new BusinessException('转换微信accessToken数据失败');
        }

        // check response
        if (!empty($responseData['errcode']) && $responseData['errcode'] !== 0) {
            throw new BusinessException($responseData['errmsg']);
        }

        // save cache
        $media_id = $responseData['media_id'];
        Cache::set($key, $media_id);

        // 返回
        return $media_id;
    }

    /**
     * addDraft
     * @param array $data
     * @param string $accessToken
     * @return string
     * @throws BusinessException
     * @link https://developers.weixin.qq.com/doc/offiaccount/Draft_Box/Add_draft.html
     */
    public static function addDraft(array $data, string $accessToken): string
    {
        // api地址
        $api = "https://api.weixin.qq.com/cgi-bin/draft/add?access_token={$accessToken}";

        // 发起请求
        $sendData = [
            'articles' => [$data]
        ];
        $response = curl($api, json_encode($sendData, JSON_UNESCAPED_UNICODE), false);
        if (!$response) {
            throw new BusinessException('请求微信addDraft接口失败');
        }
        $responseData = json_decode($response, true);
        if (!$responseData) {
            throw new BusinessException('转换微信accessToken数据失败');
        }

        // check response
        if (!empty($responseData['errcode']) && $responseData['errcode'] !== 0) {
            throw new BusinessException($responseData['errmsg']);
        }

        // 返回
        return $responseData['media_id'];
    }

    /**
     * freePublish
     * @param string $mediaId
     * @param string $accessToken
     * @throws BusinessException
     */
    public static function freePublish(string $mediaId, string $accessToken)
    {
        // api地址
        $api = "https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token={$accessToken}";

        // 发起请求
        $sendData = [
            'media_id' => $mediaId
        ];
        $response = curl($api, json_encode($sendData, JSON_UNESCAPED_UNICODE), false);
        if (!$response) {
            throw new BusinessException('请求微信freePublish接口失败');
        }
        $responseData = json_decode($response, true);
        if (!$responseData) {
            throw new BusinessException('转换微信freePublish数据失败');
        }

        // check response
        if (!empty($responseData['errcode']) && $responseData['errcode'] !== 0) {
            throw new BusinessException($responseData['errmsg']);
        }
    }
}